# --- Logging ---
$LogFile = "C:\ProgramData\FileWave\Logs\RemoveLocalUser_FullCleanup.log"
Start-Transcript -Path $LogFile -Append

# --- Read Environment Variable ---
$Username = $env:USERNAME

# --- Validate Input ---
if (-not $Username) {
    Write-Error "Environment variable 'USERNAME' is not set. Cannot proceed with account removal."
    Stop-Transcript
    exit 1
}

try {
    # Check if the user exists
    $User = Get-LocalUser -Name $Username -ErrorAction SilentlyContinue
    if (-not $User) {
        Write-Host "User '$Username' does not exist. Nothing to remove."
    }
    else {
        # Disable the user before deletion (recommended for safety in staged deployments)
        Disable-LocalUser -Name $Username
        Write-Host "User '$Username' has been disabled."

        # Remove the local user
        Remove-LocalUser -Name $Username
        Write-Host "User '$Username' has been removed successfully."
    }

    # Define expected profile path
    $UserProfilePath = Join-Path -Path "C:\Users" -ChildPath $Username

    # Remove the user's profile directory if it exists
    if (Test-Path -Path $UserProfilePath) {
        try {
            Remove-Item -Path $UserProfilePath -Recurse -Force -ErrorAction Stop
            Write-Host "Profile directory '$UserProfilePath' removed successfully."
        }
        catch {
            Write-Warning "Failed to remove profile directory '$UserProfilePath': $_"
        }
    }
    else {
        Write-Host "Profile directory '$UserProfilePath' not found. Skipping."
    }
}
catch {
    Write-Error "An error occurred during user removal: $_"
}
finally {
    Stop-Transcript
}